<template>
  <div class="dashboard-container">
    <!-- 部门生产状况图表 -->
    <div class="chart-container">
      <div id="productionStatus" class="chart"></div>
    </div>
    
    <!-- 部门生产详情图表 -->
    <div class="chart-container">
      <div id="productionDetail" class="chart"></div>
    </div>
    
    <!-- 部门人员情况图表 -->
    <div class="chart-container">
      <div id="personnelStatus" class="chart"></div>
    </div>
    
    <!-- 部门设备状况图表 -->
    <div class="chart-container">
      <div id="equipmentStatus" class="chart"></div>
    </div>
    
    <!-- 部门物料状况图表 -->
    <template v-for="(deptData, deptName) in materialStatusData" :key="deptName">
      <div class="chart-container">
        <div :id="`materialStatus-${deptName}`" class="chart"></div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

// 初始化图表实例
let productionStatusChart: echarts.ECharts
let productionDetailChart: echarts.ECharts
let personnelStatusChart: echarts.ECharts
let equipmentStatusChart: echarts.ECharts
// let materialStatusChart: echarts.ECharts // 移除单个图表实例

// 存储物料统计数据和图表实例
const materialStatusData = ref<any>(null)
const materialCharts: { [key: string]: echarts.ECharts } = {}

// 获取各类数据的函数
const fetchProductionStatus = async () => {
  const response = await axios.get(import.meta.env.VITE_API_URL + 'dashboard/productionStatus')
  const data = response.data
  
  productionStatusChart = echarts.init(document.getElementById('productionStatus'))
  productionStatusChart.setOption({
    title: { text: '各部门生产状况' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['总计划数', '已完成数', '完成率'] },
    xAxis: { type: 'category', data: data.map((item: any) => item.deptName) },
    yAxis: [
      { type: 'value', name: '数量' },
      { type: 'value', name: '完成率', axisLabel: { formatter: '{value}%' } }
    ],
    series: [
      {
        name: '总计划数',
        type: 'bar',
        data: data.map((item: any) => item.totalPlans)
      },
      {
        name: '已完成数',
        type: 'bar',
        data: data.map((item: any) => item.completedPlans)
      },
      {
        name: '完成率',
        type: 'line',
        yAxisIndex: 1,
        data: data.map((item: any) => (item.completionRate * 100).toFixed(2))
      }
    ]
  })
}

const fetchProductionDetail = async (deptId: number = 1) => {
  const response = await axios.get(import.meta.env.VITE_API_URL + `dashboard/productionDetail?deptId=${deptId}`)
  const data = response.data
  
  productionDetailChart = echarts.init(document.getElementById('productionDetail'))
  productionDetailChart.setOption({
    title: { text: '部门生产详情' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['计划数量', '实际数量'] },
    xAxis: { 
      type: 'category',
      data: data.map((item: any) => item.productName),
      axisLabel: { interval: 0, rotate: 45 }
    },
    yAxis: { type: 'value', name: '数量' },
    series: [
      {
        name: '计划数量',
        type: 'bar',
        data: data.map((item: any) => item.plannedQuantity)
      },
      {
        name: '实际数量',
        type: 'bar',
        data: data.map((item: any) => item.actualQuantity)
      }
    ]
  })
}

const fetchPersonnelStatus = async () => {
  const response = await axios.get(import.meta.env.VITE_API_URL + 'dashboard/personnelStatus')
  const data = response.data
  
  personnelStatusChart = echarts.init(document.getElementById('personnelStatus'))
  personnelStatusChart.setOption({
    title: { text: '各部门人员情况' },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [
      {
        type: 'pie',
        radius: '70%',
        data: data.map((item: any) => ({
          name: item.deptName ? item.deptName : "未分配",
          value: item.personnelCount
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

const fetchEquipmentStatus = async () => {
  const response = await axios.get(import.meta.env.VITE_API_URL + 'dashboard/equimentStatus')
  const data = response.data
  
  equipmentStatusChart = echarts.init(document.getElementById('equipmentStatus'))
  equipmentStatusChart.setOption({
    title: { text: '各部门设备状况' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['总设备数', '报废设备数', '报废率'] },
    xAxis: { type: 'category', data: data.map((item: any) => item.deptName) },
    yAxis: [
      { type: 'value', name: '数量' },
      { type: 'value', name: '报废率', axisLabel: { formatter: '{value}%' } }
    ],
    series: [
      {
        name: '总设备数',
        type: 'bar',
        data: data.map((item: any) => item.totalEquipments)
      },
      {
        name: '报废设备数',
        type: 'bar',
        data: data.map((item: any) => item.scrapEquipments)
      },
      {
        name: '报废率',
        type: 'line',
        yAxisIndex: 1,
        data: data.map((item: any) => (item.scrapRate * 100).toFixed(2))
      }
    ]
  })
}

const fetchMaterialStatus = async () => {
  const response = await axios.get(import.meta.env.VITE_API_URL + 'dashboard/materialStatus')
  const data = response.data
  materialStatusData.value = data // 存储数据

  // 在DOM更新后为每个部门创建图表
  nextTick(() => {
    Object.keys(data).forEach((deptName: string) => {
      const chartDom = document.getElementById(`materialStatus-${deptName}`)
      if (chartDom) {
        // 销毁旧的图表实例（如果存在）
        if (materialCharts[deptName]) {
          materialCharts[deptName].dispose()
        }
        const chart = echarts.init(chartDom)
        materialCharts[deptName] = chart // 存储图表实例
        chart.setOption({
          title: { text: `${deptName}物料状况` },
          tooltip: { trigger: 'item' },
          series: [
            {
              name: deptName,
              type: 'pie',
              radius: '50%',
              center: ['50%', '50%'],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              data: data[deptName].map((item: any) => ({
                name: item.materialType,
                value: item.materialCount
              }))
            }
          ]
        })
      }
    })
  })
}

// 初始化所有图表
onMounted(() => {
  fetchProductionStatus()
  fetchProductionDetail()
  fetchPersonnelStatus()
  fetchEquipmentStatus()
  fetchMaterialStatus()
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    productionStatusChart?.resize()
    productionDetailChart?.resize()
    personnelStatusChart?.resize()
    equipmentStatusChart?.resize()
    // materialStatusChart?.resize() // 移除单个图表调整
    // 调整所有物料图表大小
    Object.values(materialCharts).forEach(chart => chart.resize())
  })
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.chart-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart {
  width: 100%;
  height: 400px;
}

/* 让物料状况图表占据整行 */
.chart-container:last-child {
  grid-column: 1 / -1;
}
</style>